package com.enqualcomm.kids.mvp.terminalinfo;

import android.content.Context;

import com.enqualcomm.kids.R;
import com.enqualcomm.kids.bean.StringMessage;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.network.socket.response.QueryUserTerminalInfoResult;

import common.utils.MyLogger;
import de.greenrobot.event.EventBus;

/**
 * Created by Sunzhigang on 2015/12/21.
 *
 */
public class Presenter implements TerminalInfoHandler {

    private String terminalid;
    private ITerminalInfoModel model;
    private ITerminalInfoView view;
    private UserTerminalDefault userTerminalDefault;
    private AppDefault appDefault;
    QueryUserTerminalInfoResult.Data minfo;
    private Context context;

    public Presenter(String terminalid, Context context) {
        this.terminalid = terminalid;
        this.context = context;
        userTerminalDefault = new UserTerminalDefault(terminalid);
        appDefault = new AppDefault();
        model = new TerminalInfoModel();
    }

    public void attachView(ITerminalInfoView view) {
        this.view = view;
        QueryUserTerminalInfoResult.Data info = userTerminalDefault.getInfo();
        if (info == null) {
            model.getTerminalInfo(appDefault.getUserkey(), terminalid, this);
        } else {
            view.showTerminalInfo(info);
        }
    }

    public void updateTerminalInfo(QueryUserTerminalInfoResult.Data info) {
        model.setTerminalInfo(appDefault.getUserkey(), terminalid, info, this);
        minfo = info;
    }

    public void detachView() {
        this.view = null;
    }


    @Override
    public void getTerminalInfoSuccess(QueryUserTerminalInfoResult.Data info) {
        view.showTerminalInfo(info);
    }

    @Override
    public void setTerminalInfoSuccess() {
        view.showToast(context.getString(R.string.terminal_info_set_success));
        userTerminalDefault.setInfo(minfo);
        view.showTerminalInfo(minfo);
        EventBus.getDefault().post(new StringMessage(StringMessage.INFO_UPDATED));
    }

    @Override
    public void getTerminalInfoFailed(String message) {
        view.showToast(context.getString(R.string.app_no_connection));
    }

    @Override
    public void setTerminalInfoFailed(String message) {
        view.showToast(context.getString(R.string.app_no_connection));
    }

    public void onStop() {
        model.onStop();
    }
}
